﻿
using Abp.AspNetCore.Mvc.Controllers;
using Abp.Domain.Repositories;
using Abp.UI;
using Camc.Quality.Bop;
using Camc.Quality.Bop.Dto;
using Camc.Quality.Dto.TableReturnDto.Technique;
using Camc.Quality.ITech;
using Camc.Quality.Quality;
using Camc.Quality.Web.Controllers;
using Camc.Quality.Web.Helpers;
using ICSharpCode.SharpZipLib.Zip;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using NaturalSort.Extension;
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Drawing;
using System.Drawing.Imaging;
using System.IO;
using System.Linq;
using System.Security.Cryptography;
using System.Text;
using System.Threading.Tasks;


namespace FileStorage.Controllers
{
    public class UploadController : QualityControllerBase
    {
        private readonly TechProcessAppService _techProcess;

      //  private readonly TechProcessAppService _techProcess =new TechProcessAppService();

        // private readonly ITechProcess _techProcess = new TechProcessAppService();
        private readonly BopNodeAppService _bopNodeAppService;
        private readonly IRepository<BopDesc, Guid> _bopDescRepository;
        protected IHttpContextAccessor httpContext;
        private int ImageWidth;
        private int ImageHeight;
        //TechProcessAppService techProcess
        public UploadController(BopNodeAppService bopNodeAppService,
            IRepository<BopDesc, Guid> bopDescRepository, IHttpContextAccessor _httpContext, TechProcessAppService techProcess
          )
        {
            _bopNodeAppService = bopNodeAppService;
            _bopDescRepository = bopDescRepository;
            httpContext = _httpContext;
            _techProcess = techProcess;


        }
        /// <summary>
        /// 获取缓存路径
        /// </summary>
        /// <returns></returns>
        private DirectoryInfo GetCachePath()
        {
            string fileSaveRootDir = ConfigHelper.GetAppSetting("App", "FileRootPath");
            //文件保存的路径(应用的工作目录+文件夹相对路径);
            string fileRootPath = Environment.CurrentDirectory + "/wwwroot/" + fileSaveRootDir;
            var fileSavePath = new DirectoryInfo(Path.Combine(fileRootPath, "UploadCache"));

            if (!fileSavePath.Exists)
            {
                fileSavePath.Create();
            }
            return fileSavePath;
        }

        //获取压缩包保存路径
        private DirectoryInfo GetDestPath()
        {
            string fileSaveRootDir = ConfigHelper.GetAppSetting("App", "FileRootPath");
            //文件保存的路径(应用的工作目录+文件夹相对路径);
            string fileRootPath = Environment.CurrentDirectory + "/wwwroot/" + fileSaveRootDir;
            var fileSavePath = new DirectoryInfo(fileRootPath);
            if (!fileSavePath.Exists)
            {
                fileSavePath.Create();
            }
            return fileSavePath;
        }
        [HttpPost]
        [Route("UploadChunk")]
        public async Task<ActionResult> UploadChunk()
        {
            if (httpContext.HttpContext.Request.Form.Files.Count <= 0)
            {
                throw new UserFriendlyException("未找到需要保存文件");
            }
            var file = httpContext.HttpContext.Request.Form.Files[0];
            var totalCount = int.Parse(httpContext.HttpContext.Request.Form["total"].ToString());
            var current = int.Parse(httpContext.HttpContext.Request.Form["current"].ToString());
            var md5 = httpContext.HttpContext.Request.Form["md5"].ToString();
            var di = GetCachePath();
            var cachePathName = Path.GetFileNameWithoutExtension(file.FileName);
            var partFileName = $"{file.FileName}.part{current}";
            var outputPath = Path.Combine(di.FullName, cachePathName);
            var CacheDi = new DirectoryInfo(outputPath);
            var cacheDir = new DirectoryInfo(outputPath);
            if (!cacheDir.Exists)
            {
                cacheDir.Create();
            }
            using (var stream = file.OpenReadStream())
            {
                try
                {
                    FileStream outputStream = new FileStream(Path.Combine(outputPath, partFileName), FileMode.OpenOrCreate);
                    stream.CopyTo(outputStream);
                    outputStream.Close();
                }
                catch (Exception)
                {
                    //删除缓存文件
                    CacheDi.Delete(true);
                    throw new UserFriendlyException("保存文件失败");
                }
            }
            var copmare = new NaturalSortComparer(StringComparison.OrdinalIgnoreCase);
            var files = CacheDi.GetFiles().OrderBy(c => c.Name, copmare).ToList();
            if (files.Count == totalCount)
            {
                //合并文件并调用方法
                var mergeOutputDi = GetDestPath();
                var mergeOutputPath = Path.Combine(mergeOutputDi.FullName, file.FileName);
                FileStream outputStream = new FileStream(mergeOutputPath, FileMode.OpenOrCreate);
                files.ForEach(it =>
                {
                    using (FileStream stream = new FileStream(it.FullName, FileMode.Open, FileAccess.Read))
                    {
                        stream.CopyTo(outputStream);
                    }
                });
                outputStream.Close();
                //删除临时文件
                CacheDi.Delete(true);
                await Upload(new FileInfo(mergeOutputPath), md5);
            }
            //else
            //{
            //    throw new UserFriendlyException("解压文件失败");
            //}
            return Ok("上传成功!");
        }

        string[] formatArray = { ".zip", ".7z" };
        [HttpPost]
        [Route("upload")]
        [Microsoft.AspNetCore.Mvc.DisableRequestSizeLimit]
        public async Task<ActionResult> Upload(FileInfo fileInfo, string md5)
        {
            string uniqueFileName = null;
            string message = "";
            if (fileInfo.Exists)
            {

                //文件格式
                var fileExtension = Path.GetExtension(fileInfo.FullName);
                if (!formatArray.Contains(fileExtension))
                {
                    return new BadRequestObjectResult("上传文件格式错误");
                }
                //文件名称
                var jsonName = fileInfo.Name.Split('.')[0];
                //读取文件保存的根目录
                string fileSaveRootDir = ConfigHelper.GetAppSetting("App", "FileRootPath");
                //文件保存的路径(应用的工作目录+文件夹相对路径);
                string fileSavePath = Environment.CurrentDirectory + "/wwwroot/" + fileSaveRootDir;
                if (!Directory.Exists(fileSavePath))
                {
                    Directory.CreateDirectory(fileSavePath);
                }
                uniqueFileName = jsonName + fileExtension;
                string filePath = Path.Combine(fileSavePath, uniqueFileName);
                //fileInfo.CopyTo(filePath);
                //using (var fileStream = new FileStream(filePath, FileMode.Create))
                //{
                //    fileInfo.CopyTo(fileStream);
                //    fileStream.Flush();
                //}

                //using (var fileStream = new FileStream(filePath, FileMode.Create))
                //{
                //    file.CopyTo(fileStream);
                //    fileStream.Flush();
                //}
                //获取传入文件的md5值
                var md = GetMD5HashFromFile(filePath);
                //判断上传的文件的md5是否相同
                if (md == md5)
                {
                    //获得当前文件夹名称
                    var fileSave = uniqueFileName.Split('.')[0];
                    //解压文件
                    //ConfigHelper.CreateLogText("解压文件:" + "@filePath:" + @filePath + ",@fileSavePath:" + @fileSavePath);
                    (new FastZip()).ExtractZip(@filePath, @fileSavePath + "/" + fileSave, "");
                    //找更改记录版本
                    //var directory = new DirectoryInfo(fileSavePath + "/" + fileSave + "/");
                    //var logFiles = directory.GetFiles("*.json_version*", SearchOption.AllDirectories).ToList();
                    //if (logFiles.Count > 0)
                    //{
                    //    string replaceData = jsonName + ".json_version";
                    //    var filterFile = logFiles.Select(x => new { x, num = Convert.ToInt32(x.Name.Replace(replaceData, "")) }).OrderByDescending(x => x.num).Select(x => x.x).ToList();
                    //    List<int> num = logFiles.Select(x => new { x, num = Convert.ToInt32(x.Name.Replace(replaceData, "")) }).OrderByDescending(x => x.num).Select(x => x.num).ToList();
                    //    var Json = filterFile[0].FullName;
                    //    message = await _techProcess.AnalysisReturnJson(Json, jsonName, num[0].ToString());
                    //}
                    //else
                    //{
                    //    return Content("无相关版本文件");

                    //}
                    //   var josnname = file.FileName.Split('.')[0];
                    //  var Json = fileSavePath + "/" + fileSave + "/" + jsonName + ".json";

                    var Json = fileSavePath + "/" + fileSave + "/" + jsonName + ".json";

                    message = await _techProcess.AnalysisReturnJson(Json, jsonName);
                    //var directory = new DirectoryInfo(fileSavePath + "/" + fileSave + "/");
                    //var logFiles = directory.GetFiles("*.json_version*", SearchOption.AllDirectories).ToList();
                    //if (logFiles.Count > 0)
                    //{
                    //    //string replaceData = jsonName + ".json_version";


                    //}
                    //解析文件
                    if (message == "true")
                    {
                        return Ok(jsonName + "上传成功!");
                    }
                    else 
                    {
                        return Content("上传失败");
                    }
                  
                }
                else
                {
                    throw new UserFriendlyException("Md5值不符,请重新上传");
                }
            }
            else
            {
                throw new UserFriendlyException("文件不能为空");
            }



        }

        [HttpPost]
        [Route("uploadNomd5")]
        [Microsoft.AspNetCore.Mvc.DisableRequestSizeLimit]
        public async Task<ActionResult> UploadNomd5Async(IFormFile file)
        {
            string uniqueFileName = null;
            if (file != null)
            {
                //文件格式
                var fileExtension = Path.GetExtension(file.FileName);
                if (!formatArray.Contains(fileExtension))
                {
                    return new BadRequestObjectResult("上传文件格式错误");
                }
                //文件名称
                var jsonName = file.FileName.Split('.')[0];
                //读取文件保存的根目录
                string fileSaveRootDir = ConfigHelper.GetAppSetting("App", "FileRootPath");
                //文件保存的路径(应用的工作目录+文件夹相对路径);
                string fileSavePath = Environment.CurrentDirectory + "/wwwroot/" + fileSaveRootDir;
                if (!Directory.Exists(fileSavePath))
                {
                    Directory.CreateDirectory(fileSavePath);
                }
                uniqueFileName = jsonName + fileExtension;
                string filePath = Path.Combine(fileSavePath, uniqueFileName);
                using (var fileStream = new FileStream(filePath, FileMode.Create))
                {
                    file.CopyTo(fileStream);
                    fileStream.Flush();
                }
                //获取传入文件的md5值
                //var md = GetMD5HashFromFile(filePath);
                //判断上传的文件的md5是否相同
                //  if (md == md5)
                // {
                //获得当前文件夹名称
                var fileSave = uniqueFileName.Split('.')[0];
                //解压文件
                (new FastZip()).ExtractZip(@filePath, @fileSavePath + "/" + fileSave, "");
                //   var josnname = file.FileName.Split('.')[0];
                var Json = fileSavePath + "/" + fileSave + "/" + jsonName + ".json";
                //解析文件
                string message = await _techProcess.AnalysisReturnJson(Json, jsonName);
                if (message == "true")
                {
                    return Ok(jsonName + "上传成功!");
                }
                else
                {
                    return Ok(jsonName + "上传失败!");
                }
                //  }
                //  else
                //  {
                //      throw new UserFriendlyException("Md5值不符,请重新上传");
                //  }

            }
            else
            {
                throw new UserFriendlyException("文件不能为空");
            }
        }



        [HttpPost]
        [Route("uploadBigFileNomd5")]
        [Microsoft.AspNetCore.Mvc.DisableRequestSizeLimit]
        public async Task<ActionResult> UploadBigFileNomd5Async(string file)
        {
            if (!string.IsNullOrEmpty(file))
            {
                string rootPath = Environment.CurrentDirectory + "/wwwroot/";
                //文件格式
                var fileExtension = Path.GetExtension(file);
                if (!formatArray.Contains(fileExtension))
                {
                    return new BadRequestObjectResult("上传文件格式错误");
                }
                string fileSaveRootDir = ConfigHelper.GetAppSetting("App", "BigFileRootPath");

                string fileSaveRootDirTarger = ConfigHelper.GetAppSetting("App", "FileRootPath");

                string fileSavePath = rootPath + fileSaveRootDir;

                if (!Directory.Exists(fileSavePath))
                {
                    Directory.CreateDirectory(fileSavePath);
                }
                //文件名称
                var jsonName = file.Split('.')[0];
                //文件路径
                string ZipPath = fileSavePath + "/" + file;
                //目标路径
                string FilePath = rootPath + fileSaveRootDirTarger + "/" + jsonName;
                //如果不需要嵌入到接口 去掉用exe解压
                if (!ZipOpen(ZipPath, FilePath, true))
                {
                    return Ok(jsonName + "解压失败!");
                   
                }
                //var directory = new DirectoryInfo(FilePath + "/");
                //var logFiles = directory.GetFiles("*.json", SearchOption.AllDirectories).ToList();
                //List<BackTaskFormat> Tasks = new List<BackTaskFormat>();
                //for (int i = 0; i < logFiles.Count; i++)
                //{
                //    var techName = logFiles[i].Name.Split('.')[0];
                //    if (techName.Replace("_", "") != jsonName.Replace("_", ""))
                //    {
                //        BackTaskFormat backTask = new BackTaskFormat();
                //        backTask.TechniqueNum = techName;
                //        //曲冰修改
                //        backTask.FilePath = Environment.CurrentDirectory + "/wwwroot/" + fileSaveRootDirTarger + "/" + jsonName+"/" + techName + "/" + techName + ".json";
                //        Tasks.Add(backTask);
                //    }
                //}
                //BackTaskInput taskInput = new BackTaskInput();
                //taskInput.BackTask = Tasks;

                //   var josnname = file.FileName.Split('.')[0];
                var Json = FilePath+ "/" + jsonName + ".json";
                //解析文件
                string message = await _techProcess.AnalysisReturnJson(Json, jsonName);
                if (message == "true")
                {
                    System.IO.File.Delete(ZipPath);
                    return Ok(jsonName + "上传成功!");
                }
                else
                {
                    return Ok(jsonName + "上传失败!");
                }
                //  }
                //  else
                //  {
                //      throw new UserFriendlyException("Md5值不符,请重新上传");
                //  }

            }
            else
            {
                throw new UserFriendlyException("文件不能为空");
            }
        }

        private bool ZipOpen(string zipPath, string filePath, bool v)
        {
            try
            {
                UploadHelper.UnZip(zipPath, filePath, null, true);
                return true;
            }
            catch
            {
                return false;
            }
        }
        //[HttpPost]
        //[Route("uploadBop")]
        //public async Task<ActionResult> UploadBop(IFormFile file, string md5)
        //{
        //    string uniqueFileName = null;

        //    if (file != null)
        //    {
        //        //文件格式
        //        var fileExtension = Path.GetExtension(file.FileName);
        //        if (!formatArray.Contains(fileExtension))
        //        {
        //            return new BadRequestObjectResult("上传文件格式错误");
        //        }
        //        string jsonName = "";

        //        //文件名称
        //        var fileTextName = file.FileName.Split('.')[0];

        //        if (fileTextName.Contains("_"))
        //        {
        //            jsonName = fileTextName.Substring(0, fileTextName.Length - 2);
        //            string keyWord = "_";
        //            int index = 0;
        //            int count = 0;
        //            while ((index = fileTextName.IndexOf(keyWord, index)) != -1)
        //            {
        //               count++;               
        //               index = index + keyWord.Length;
        //            }
        //            if (count == 2)
        //            {
        //                var array = fileTextName.Split('_');
        //                var modelName = array[0];
        //                var lotName = array[1];
        //                var edtion = Convert.ToInt64(array[2]);
        //                var bopDesc = await _bopDescRepository.FirstOrDefaultAsync(d => d.ModelName == modelName && d.LotNo == lotName);
        //                if (bopDesc != null)
        //                {
        //                    var treeVersion = await _treeVersionLogRepository.FirstOrDefaultAsync(d => d.ModelId == bopDesc.ModelId && d.LotNoId == bopDesc.LotNoId && d.Type == 1);
        //                    if (treeVersion != null)
        //                    {
        //                        var treeEdition = treeVersion.Version;
        //                        if (edtion != (treeEdition + 1))
        //                        {
        //                            return new BadRequestObjectResult("当前版本不符合,只能接收版本" + (treeEdition + 1).ToString());
        //                        }
        //                    }
        //                    else
        //                    {
        //                        if (edtion == 1)
        //                        {
        //                            TreeVersionLog versionLog = new TreeVersionLog();
        //                            versionLog.ModelId = bopDesc.ModelId;
        //                            versionLog.LotNoId = bopDesc.LotNoId;
        //                            versionLog.Type = 1;
        //                            versionLog.Version = 1;
        //                            await _treeVersionLogRepository.InsertAsync(versionLog);
        //                        }
        //                        else
        //                        {
        //                            return new BadRequestObjectResult("导入数据包版本不正确！");
        //                        }
        //                    }
        //                }
        //                else
        //                {
        //                    return new BadRequestObjectResult("导入数据包名称不正确！");
        //                }

        //            }
        //            else
        //            {
        //                return new BadRequestObjectResult("导入数据包名称不正确！");
        //            }
        //        }
        //        else
        //        {
        //            throw new UserFriendlyException("导入数据包名称不正确！");
        //        }


        //        //读取文件保存的根目录
        //        string fileSaveRootDir = ConfigHelper.GetAppSetting("App", "BopFileRootPath");


        //        //文件保存的路径(应用的工作目录+文件夹相对路径);
        //        string fileSavePath = Environment.CurrentDirectory + "/wwwroot/" + fileSaveRootDir;
        //        if (!Directory.Exists(fileSavePath))
        //        {
        //            Directory.CreateDirectory(fileSavePath);
        //        }



        //        uniqueFileName = jsonName + fileExtension;
        //        string filePath = Path.Combine(fileSavePath, uniqueFileName);
        //        using (var fileStream = new FileStream(filePath, FileMode.Create))
        //        {
        //            file.CopyTo(fileStream);
        //            fileStream.Flush();
        //        }
        //        //获取传入文件的md5值
        //        var md = GetMD5HashFromFile(filePath);
        //        //判断上传的文件的md5是否相同
        //        if (md == md5)
        //        {
        //            //获得当前文件夹名称
        //            var fileSave = uniqueFileName.Split('.')[0];

        //            String DateStr = System.DateTime.Now.ToString("yyyyMMdd");
        //            //解压文件
        //            (new FastZip()).ExtractZip(@filePath, @fileSavePath + "/" + fileSave + "/" + DateStr, "");
        //            //   var josnname = file.FileName.Split('.')[0];
        //            var Json = fileSavePath + "/" + fileSave + "/" + DateStr + "/" + jsonName + ".json";


        //            var directory = new DirectoryInfo(fileSavePath + "/" + fileSave + "/"+ DateStr+"/");
        //            var logFiles = directory.GetFiles("*.json", SearchOption.AllDirectories).ToList();
        //            List<BackTaskFormat> Tasks = new List<BackTaskFormat>();
        //            for (int i = 0; i < logFiles.Count; i++)
        //            {
        //                var techName = logFiles[i].Name.Split('.')[0];
        //                if (techName.Replace("_","") != jsonName.Replace("_", ""))
        //                {
        //                    BackTaskFormat backTask = new BackTaskFormat();
        //                    backTask.TechniqueNum = techName;
        //                    backTask.FilePath= fileSavePath + "/" + fileSave + "/" + DateStr + "/"+ techName+"/"+ techName+"/"+ techName+".json";
        //                    Tasks.Add(backTask);
        //                }
        //            }
        //            BackTaskInput taskInput = new BackTaskInput();
        //            taskInput.BackTask = Tasks;

        //            //解析文件
        //            await _techProcess.BatchAnalyJson(taskInput);

        //            string fileBopRootDir = ConfigHelper.GetAppSetting("App", "FileRootPath");


        //            for (int i = 0; i < Tasks.Count; i++)
        //            {
        //                string sourcePatch = fileSavePath + "/" + fileSave + "/" + DateStr + "/" + Tasks[i].TechniqueNum + "/"+ Tasks[i].TechniqueNum+"/";
        //                string srcPatch = Environment.CurrentDirectory + "/wwwroot/" + fileBopRootDir + "/" + Tasks[i].TechniqueNum + "/";
        //                if (!Directory.Exists(srcPatch))
        //                {
        //                    Directory.CreateDirectory(srcPatch);
        //                    if (CopyDir(sourcePatch, srcPatch))
        //                    {
        //                    }
        //                    else
        //                    {
        //                        throw new UserFriendlyException("拷贝文件失败！");
        //                    }
        //                }
        //                else
        //                {
        //                    DirectoryInfo root = new DirectoryInfo(sourcePatch);
        //                    var dics = root.GetDirectories();
        //                    for (int k = 0; k < dics.Length; k++)
        //                    {
        //                        string tempPath = srcPatch + dics[i].Name + "/";
        //                        if (!Directory.Exists(tempPath))
        //                        {
        //                            Directory.CreateDirectory(srcPatch);
        //                        }
        //                        if (CopyDir(dics[i].FullName, tempPath))
        //                        {
        //                        }
        //                        else
        //                        {
        //                            throw new UserFriendlyException("拷贝文件失败！");
        //                        }
        //                    }
        //                    //Directory.Delete(srcPatch, true);
        //                }
        //            }
        //            return Ok(jsonName + "上传成功!");

        //        }
        //        else
        //        {
        //            throw new UserFriendlyException("Md5值不符,请重新上传");
        //        }

        //    }
        //    else
        //    {
        //        throw new UserFriendlyException("文件不能为空");
        //    }
        //}


        //[HttpPut]
        //[Route("postUploadAsync")]
        //public async Task<IActionResult> PostUploadAsync([FromForm] IFormFileCollection files,Guid NodeId,int option=0)
        //{
        //    if (files == null)
        //    {
        //        return Ok("请选择图片!");
        //    }
        //    if (files.Count==0)
        //    {
        //        return Ok("请选择图片!");
        //    }
        //    List<IFormFile> formFiles = new List<IFormFile>();
        //    foreach (var file in files)
        //    {
        //        formFiles.Add(file);
        //    }
        //    CommonImageInput common = new CommonImageInput();
        //    common.files = formFiles;
        //    common.NodeId = NodeId;
        //    if (option == 0)
        //    {
        //       var temp=  await _bopNodeAppService.OnPostUploadAsync(common);
        //       return Ok(temp);
        //    }
        //    else
        //    {
        //        await _bopNodeAppService.SaveUploadPic(common);
        //        return Ok("上传成功!");
        //    }

        //}

        /// <summary>
        /// 获取文件的MD5码
        /// </summary>
        /// <param name="fileName">传入的文件名（含路径及后缀名）</param>
        /// <returns></returns>
        public string GetMD5HashFromFile(string fileName)
        {
            try
            {
                FileStream file = new FileStream(fileName, FileMode.Open);
                MD5 md5 = new MD5CryptoServiceProvider();
                byte[] retVal = md5.ComputeHash(file);
                file.Close();
                StringBuilder sb = new StringBuilder();
                for (int i = 0; i < retVal.Length; i++)
                {
                    sb.Append(retVal[i].ToString("x2"));
                }
                return sb.ToString();
            }
            catch (Exception ex)
            {
                throw new Exception("GetMD5HashFromFile() fail,error:" + ex.Message);
            }
        }




    }
}
